package com.fresh.liangyi.controller.client;

import com.fresh.liangyi.model.domain.Goods;
import com.fresh.liangyi.service.GoodsService;
import com.fresh.liangyi.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    //根据id获取详情
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id,
                         Model model){
        Goods goods=goodsService.selectById(id);
        model.addAttribute("goods",goods);
        return "client/goodsDetails";
    }


    //加入购物车
    @PostMapping("/addCart")
    @ResponseBody
    public String addCartGoods(@RequestParam Integer goodsId){
        goodsService.addCartGoods(UserUtils.getUser().getId(),goodsId);
        return "success";
    }
    //获取全部商品
    @GetMapping("/all")
    @ResponseBody
    public List<Goods> getAll(Model model){
        List<Goods> goodsList=goodsService.selectGoodsAll();
        model.addAttribute("goodsList",goodsList);
        return goodsList;
    }

    //搜索商品
    @GetMapping(value = {"/search","/search"})
    public String searchGoods(@RequestParam(value = "keyword",required = false) String keyword,Model model){
        List<Goods> goodsList=null;
        if (keyword == null||StringUtils.isBlank(keyword)) {
            goodsList=goodsService.selectGoodsAll();
        }else{
            goodsList=goodsService.selectByKeyword(keyword);
        }
        model.addAttribute("goodsList",goodsList);
        return "client/search_result";
    }

    @PostMapping("/update")
    @ResponseBody
    public Goods updateGoods(@RequestParam(value = "goods") Goods goods,
                             Model model){
        return goodsService.updateGoods(goods);
    }
}
